<template>
  <div class="GanttChart">
    <div class="operation">
      <div class="operation-date">
        <el-button
          class="arrange-btn"
          size="medium"
          icon="el-icon-arrow-left"
          @click="addOrReduceDate('prev')"
        />
        <div class="title">
          {{ timeTitle }}
        </div>
        <el-button
          class="arrange-btn"
          size="medium"
          icon="el-icon-arrow-right"
          @click="addOrReduceDate('next')"
        />
      </div>
      <div class="operation-save">
        <!-- <el-button class="arrange-btn saveBtn" size="medium">保存</el-button> -->
      </div>
    </div>
    <div class="showContent">
      <div class="chartTitle">
        <div class="chart-title" :class="{ active: selected === 'Ku' }">
          <div class="chart-title-name">C散射设备</div>
          <!-- <div class="chart-title-value">Ku</div> -->
        </div>
        <div class="chart-title" :class="{ active: selected === 'V/U' }">
          <div class="chart-title-name">Ku散射设备</div>
          <!-- <div class="chart-title-value">VHF/UHF</div> -->
        </div>
        <div class="chart-title" :class="{ active: selected === 'C' }">
          <div class="chart-title-name">VHF/UHF电台</div>
          <!-- <div class="chart-title-value">C</div> -->
        </div>
      </div>
      <div id="container"></div>
    </div>
  </div>
</template>

<script>
import { getTaskByDay } from "@/api/taskArrangement";
import Highcharts from "highcharts/highstock";
import HighchartsMore from "highcharts/highcharts-more";
import HighchartsDrilldown from "highcharts/modules/drilldown";
import Highcharts3D from "highcharts/highcharts-3d";
import HighchartsXRange from "highcharts/modules/xrange";
HighchartsMore(Highcharts);
HighchartsDrilldown(Highcharts);
Highcharts3D(Highcharts);
HighchartsXRange(Highcharts);
export default {
  data() {
    return {
      chart: null,
      timeTitle: "2025-2-27",
      selected: "Ku",
      options: {
        chart: {
          type: "xrange", // 官网找这个文档
          backgroundColor: "transparent", // 设置背景颜色
          // marginTop: 100, // 增加顶部边距，给时间轴留出空间
          // spacingTop: 50, // 增加顶部间距，确保时间轴不会与标题重叠
        },
        title: {
          text: "",
        },
        xAxis: {
          type: "datetime",
          min: Date.UTC(2014, 10, 21, 0, 0, 0), // 设置最小值为当天的00:00
          max: Date.UTC(2014, 10, 22, 0, 0, 0), // 设置最大值为次日的00:00，确保覆盖整个日期范围
          tickInterval: 3600 * 1000, // 刻度间隔为1小时
          labels: {
            style: {
              color: "#81e7eb", // 设置字体颜色
            },
            format: "{value:%H:%M}", // 格式化标签为小时
          },
          opposite: true, // 将时间轴放置在顶部
        },
        yAxis: {
          title: {
            text: "",
          },
          categories: ["", "", ""], //y轴名称，为空
          reversed: true, // 让最顶部的任务显示在顶部
          gridLineWidth: 1,
          gridLineColor: "#05577f", // 设置网格线的颜色，可以是任何有效的颜色表示
        },
        plotOptions: {
          series: {
            dataLabels: {
              enabled: true,
              formatter: function () {
                // 每个数据条上现实的内容！！
                // return (
                //   '<span style="font-size: 12px;">' +
                //   this.point.description +
                //   "</span><br><span>换行</span>"
                // );
                return (
                  '<span style="margin-bottom:5px;color:#fff; font-size: 12px; position: absolute; left: 0px; top: 0px">' +
                  this.point.testDict +
                  "</span></br>" +
                  '<span style="color:#fff; font-size: 12px; position: absolute; left: 10px; bottom: 0px">' +
                  this.point.taskName +
                  "&nbsp&nbsp</span>" +
                  '<span style="color:#fff; font-size: 12px; position: absolute; left: 50px; bottom: 0px">' +
                  this.point.freqType +
                  "&nbsp&nbsp</span>" +
                  '<span style="color:#fff; font-size: 12px; position: absolute; left: 100px; bottom: 0px">' +
                  this.point.endStrategy +
                  "</span>"
                );
              },
              style: {
                textOutline: false, // 关闭默认的文字描边效果
              },
            },
          },
        },
        exporting: {
          enabled: false, // 禁用导出菜单
        },
        tooltip: {
          enabled: false,
        },
        series: [
          {
            // name: '项目1',
            showInLegend: false, // 设置为 false 将移除该系列的图例
            // pointPadding: 0,
            // groupPadding: 0,
            borderColor: "gray",
            pointWidth: 50,
            data: this.chartData,
          },
        ],
      },
      chartData: [],
    };
  },
  components: {},
  props: {
    infoDateStr: {
      type: String,
      default: "",
    },
  },
  watch: {
    infoDateStr: {
      deep: true,
      handler(newVal) {
        this.timeTitle = this.formatDate(newVal);

        // 修改图标坐标轴时间
        this.changeTimeRange();
        // 查询今天时间的数据

        this.options.series[0].data = [];
        this.chart.update(this.options);
        // 重绘页面
        this.changeTimeRange();
        this.getTaskByDay();
      },
    },
  },
  computed: {},
  created() {},
  methods: {
    // 处理时间
    handleTime() {
      // 获取当前日期
      let today = new Date();

      // 获取年、月、日
      let year = today.getFullYear();
      let month = today.getMonth() + 1; // 月份是从0开始的，所以要加1
      let day = today.getDate();
      // 格式化成 YYYY-M-D 的形式
      // 注释了这里，需要解开
      this.timeTitle = `${year}-${month}-${day}`;
      console.log("this.timeTitle", this.timeTitle);
    },
    // 时间提前一天或者时间退后一天
    addOrReduceDate(str) {
      // 将日期字符串转换为 Date 对象
      let dateObj = new Date(this.timeTitle);
      if (str == "prev") {
        // 减少一天
        dateObj.setDate(dateObj.getDate() - 1);
      } else {
        // 增加一天
        dateObj.setDate(dateObj.getDate() + 1);
      }
      // 获取年、月、日
      let year = dateObj.getFullYear();
      let month = dateObj.getMonth() + 1; // 月份是从0开始的，所以要加1
      let day = dateObj.getDate();
      // 格式化成 YYYY-M-D 的形式
      this.timeTitle = `${year}-${month}-${day}`;
      // 修改图标坐标轴时间
      this.changeTimeRange();
      // 查询今天时间的数据

      this.options.series[0].data = [];
      this.chart.update(this.options);
      // 重绘页面
      this.changeTimeRange();
      this.getTaskByDay();
    },
    // 初始化highChart图
    initGanttChart() {
      this.chart = new Highcharts.Chart("container", this.options);
    },
    // 点击按钮切换时间范围的处理函数
    changeTimeRange() {
      // 将日期字符串转换为 Date 对象
      let targetDate = new Date(this.timeTitle);
      let targetTimestamp = new Date(this.timeTitle).getTime();
      // 获取年、月、日
      let minYear = targetDate.getFullYear();
      let minMonth = targetDate.getMonth() + 1; // 月份是从0开始的，所以要加1
      let minDay = targetDate.getDate();

      // 将天数+1，赋值给max时间
      // 添加一天
      // dateObj.setDate(dateObj.getDate() + 1);
      const oneDayMs = 24 * 60 * 60 * 1000;
      // 下一天的时间戳
      const nextDayTimestamp = targetTimestamp + oneDayMs;
      const nextDayDate = new Date(nextDayTimestamp);

      // 获取年、月、日
      let maxYear = nextDayDate.getFullYear();
      let maxMonth = nextDayDate.getMonth() + 1; // 月份是从0开始的，所以要加1
      let maxDay = nextDayDate.getDate();

      // 计算新的时间范围，例如切换到另一天的时间段
      // var newMin = Date.UTC(minYear, minMonth, minDay, 0, 0, 0); // 新的最小值
      // var newMax = Date.UTC(maxYear, maxMonth, maxDay, 0, 0, 0); // 新的最大值
      var newMin = targetTimestamp + 8 * 60 * 60 * 1000; // 新的最小值
      var newMax = nextDayTimestamp + 8 * 60 * 60 * 1000; // 新的最大值

      // 更新 xAxis 的 min 和 max 属性
      this.chart.xAxis[0].update({
        min: newMin,
        max: newMax,
      });
      // 重新绘制图表
      this.chart.redraw();
    },
    // 获取甘特图
    getTaskByDay() {
      getTaskByDay(this.handleDate(this.timeTitle))
        .then((res) => {
          const data = res.data;
          const code = res.code;
          if (code == 200) {
            this.$message.success("当日测试任务信息成功");
          } else {
            this.$message.error("当日测试任务信息失败");
          }
          // 若不为空
          if (data != null) {
            // 首先删除已经存在的数据
            this.chartData = [];
            Object.keys(data).forEach((group) => {
              data[group].forEach((item) => {
                let color = "";
                let testDict = "";
                let freqType = "";
                let endStrategy = "";
                switch (Number(item.testType)) {
                  case 1:
                    color = "#069fc5";
                    testDict = "话音测试";
                    break;
                  case 2:
                    color = "#0091f1";
                    testDict = "数据测试";
                    break;
                  case 3:
                    color = "#f4a461";
                    testDict = "视频测试";
                    break;
                }
                switch (Number(item.freqType)) {
                  case 1:
                    freqType = "点频";
                    break;
                  case 2:
                    freqType = "跳频";
                    break;
                  case 3:
                    freqType = "扫频";
                    break;
                }
                switch (Number(item.endStrategy)) {
                  case 1:
                    endStrategy = "截止时间优先";
                    break;
                  case 2:
                    endStrategy = "测试完成优先";
                    break;
                }
                // 组装为OBJ
                let transformedObject = {
                  x: new Date(item.startTime).getTime() + 8 * 60 * 60 * 1000,
                  x2: new Date(item.endTime).getTime() + 8 * 60 * 60 * 1000,
                  y: group - 1, //在哪一行
                  color: color,
                  testDict: testDict, //
                  taskName: item.taskName, //
                  freqType: freqType, //
                  endStrategy: endStrategy, //
                };
                this.chartData.push(transformedObject);
              });
            });
            /* 添加三个不需要展示的值用于占用位置 */
            const temArray = [
              {
                x: new Date().getTime() + 8 * 60 * 60 * 1000,
                x2: new Date().getTime() + 8 * 60 * 60 * 1000,
                y: 0,
                color: "",
                testDict: "",
                taskName: "",
                freqType: "",
                endStrategy: "",
              },
              {
                x: new Date().getTime() + 8 * 60 * 60 * 1000,
                x2: new Date().getTime() + 8 * 60 * 60 * 1000,
                y: 1,
                color: "",
                testDict: "",
                taskName: "",
                freqType: "",
                endStrategy: "",
              },
              {
                x: new Date().getTime() + 8 * 60 * 60 * 1000,
                x2: new Date().getTime() + 8 * 60 * 60 * 1000,
                y: 2,
                color: "",
                testDict: "",
                taskName: "",
                freqType: "",
                endStrategy: "",
              },
            ];
            this.chartData = this.chartData.concat(temArray);
            console.log("resres", this.chartData);
            this.options.series[0].data = this.chartData;
            this.chart.update(this.options);
            // 重绘页面
            this.changeTimeRange();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //传入时间日期“2023-01-01”会变成“2023-1-1”
    formatDate(dateString) {
      var parts = dateString.split("-");
      var year = parts[0];
      var month = parseInt(parts[1], 10); // 去除月份前导零
      var day = parseInt(parts[2], 10); // 去除日期前导零
      return `${year}-${month}-${day}`;
    },

    //传入时间日期“2023-1-1”会变成“2023-01-01”
    handleDate(dateStr) {
      const parts = dateStr.split("-");
      const year = parts[0];
      // 用padStart保证月份和日期是两位数
      const month = parts[1].padStart(2, "0");
      const day = parts[2].padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 初始化图表时添加拖拽事件监听
    initGanttChart() {
      this.chart = new Highcharts.Chart("container", this.options);

      // 获取图表容器元素
      const chartContainer = document.getElementById("container");

      // 阻止默认拖拽行为
      chartContainer.addEventListener("dragover", (e) => {
        e.preventDefault();
      });

      // 处理拖放事件
      chartContainer.addEventListener("drop", (e) => {
        e.preventDefault();
        const chart = this.chart;
        const xAxis = chart.xAxis[0];

        // 获取准确的图表位置
        const chartPosition = Highcharts.offset(chartContainer);
        const chartX = e.pageX - chartPosition.left - chart.plotLeft;
        // console.log("999e.pageX", e.pageX);
        console.log("999e.pageX", e);
        // console.log("999e.chartPosition.left", chartPosition.left);
        // console.log("999e.chart.plotLeft", chart.plotLeft);

        // 转换为时间戳（已考虑时区）
        const timestamp = xAxis.toValue(chartX);
        // 将时间戳传递回去
        this.$emit("handleDragTime", timestamp, e.offsetY);
      });
    },

    // 时间格式化方法
    formatDateTime(date) {
      return Highcharts.dateFormat("%Y-%m-%d %H:%M:%S", date);
    },

    // 计算结束时间
    calculateEndTime(startTime, durationHours) {
      const end = new Date(startTime);
      end.setHours(end.getHours() + durationHours);
      return this.formatDateTime(end);
    },
  },
  mounted() {
    this.handleTime(); // 初始化时间
    this.initGanttChart(); // 初始化甘特图
    setTimeout(() => {
      this.getTaskByDay(); //获取甘特图数据// 注释了这里，需要解开

      this.options.series[0].data = this.chartData;
      this.chart.update(this.options);
      // 重绘页面
      this.changeTimeRange();
    }, 200);
  },
};
</script>

<style lang="scss" scoped>
.GanttChart {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .operation {
    height: 3.125rem;
    line-height: 3.125rem;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    .operation-date {
      display: flex;
      align-items: center;
      margin-left: 1.25rem;
      .title {
        font-size: 1.125rem;
        padding: 0 0.9375rem;
        font-weight: 700;
      }
    }
    .operation-save {
      margin-right: 1.25rem;
    }
  }
  .showContent {
    flex: 1;
    display: flex;
    flex-direction: row;

    .chartTitle {
      width: 15.9375rem;
      margin-top: 2.5rem;
      margin-bottom: 1rem;
      display: flex;
      flex-direction: column;

      .chart-title {
        flex: 1;
        text-align: center;
        background: url("~@/assets/images/taskArrangement/normal.png") no-repeat;
        background-size: 100% 100%;
        margin: 0.4375rem 0 0.4375rem 0.3125rem;
        position: relative;
        color: #81b7eb;
        cursor: pointer;
        .chart-title-name {
          position: absolute;
          top: 1.1875rem;
          left: 0.5625rem;
          font-size: 1.375rem;
          font-weight: 700;
        }
        .chart-title-value {
          position: absolute;
          top: 0.5rem;
          left: 10.625rem;
          font-size: 1rem;
        }
      }
      .chart-title.active {
        background: url("~@/assets/images/taskArrangement/active.png") no-repeat;
        background-size: 100% 100%;
        color: #fafcfe;
      }
    }

    #container {
      height: 100%;
      flex: 1;
    }
  }
  /* 重写button样式 */
  .arrange-btn {
    color: #aedeff;
    border: 0.0625rem solid #4987e0;
    background: linear-gradient(to bottom, #0062a7, #00245f);
  }
  .arrange-btn:focus,
  .arrange-btn:hover {
    color: #00e4ff;
    border-color: #4987e0;
    background: linear-gradient(to bottom, #001a40, #003362);
  }
  .drag-list {
    position: fixed;
    right: 20px;
    top: 20px;
    z-index: 1000;

    .drag-item {
      padding: 10px 20px;
      margin: 5px;
      background: linear-gradient(to right, #ff0000 50%, #00ff00 50%);
      border: 1px solid #00e4ff;
      border-radius: 4px;
      cursor: move;
      transition: all 0.3s;

      /* &:hover {
        background: #409eff;
        color: white;
      } */
    }
  }

  // 确保图表容器可以接收拖拽事件
  #container {
    position: relative; // 重要：确保offset计算正确
    height: 100%;
    cursor: crosshair;
  }
}
</style>
